﻿//-----------------------------------------------------------------------
// <copyright file="BookFindPage.xaml.cs" company="FIT VUT">
//     Copyright (c) FIT VUT. All rights are reserved.
// </copyright>
//----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Threading;
using System.Collections.ObjectModel;
using com.google.zxing.qrcode;
using Microsoft.Devices;
using com.google.zxing.common;
using com.google.zxing;
using BookCaching.Data;

namespace BookCaching.Pages
{
    /// <summary>
    /// Page allows a user to scan a book's QR Code in order to add the book to his/her collection.
    /// </summary>
    public partial class BookFindPage : PhoneApplicationPage
    {
        private readonly DispatcherTimer timer;
        private readonly ObservableCollection<string> matches;

        private PhotoCameraLuminanceSource luminance;
        private QRCodeReader reader;
        private PhotoCamera photoCamera;

        private string qrID;

        public BookFindPage()
        {
            this.InitializeComponent();

            matches = new ObservableCollection<string>();

            //findBookExists = false;

            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(250);
            timer.Tick += (o, arg) => ScanPreviewBuffer();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            photoCamera = new PhotoCamera();
            photoCamera.Initialized += OnPhotoCameraInitialized;
            previewVideo.SetSource(photoCamera);

            CameraButtons.ShutterKeyHalfPressed += (o, arg) => photoCamera.Focus();

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            photoCamera.Initialized -= OnPhotoCameraInitialized;
            CameraButtons.ShutterKeyHalfPressed -= (o, arg) => photoCamera.Focus();
            timer.Stop();

            base.OnNavigatedFrom(e);
        }

        private void OnPhotoCameraInitialized(object sender, CameraOperationCompletedEventArgs e)
        {
            int width = Convert.ToInt32(photoCamera.PreviewResolution.Width);
            int height = Convert.ToInt32(photoCamera.PreviewResolution.Height);

            luminance = new PhotoCameraLuminanceSource(width, height);
            reader = new QRCodeReader();


            Dispatcher.BeginInvoke(() =>
            {
                previewTransform.Rotation = photoCamera.Orientation;
                timer.Start();
            });
        }

        private void ScanPreviewBuffer()
        {
            try
            {
                photoCamera.GetPreviewBufferY(luminance.PreviewBufferY);
                var binarizer = new HybridBinarizer(luminance);
                var binBitmap = new BinaryBitmap(binarizer);
                var result = reader.decode(binBitmap);
                int a = 10;
                qrID = result.Text;
                Dispatcher.BeginInvoke(() => CheckBookIDExist());
            }
            catch
            {
                return;
            }
        }

        private void client_GetBookByIDCompleted(object sender, Knihotoc_WCFService.GetBookByIDCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                return;
            }

            Knihotoc_WCFService.Book findBook = e.Result;
            if (findBook != null)
            {
                NavigationService.Navigate(new Uri("/Pages/BookFindBookDetailPage.xaml?BookID=" + qrID, UriKind.Relative));
            }

        }

        private void CheckBookIDExist()
        {
            this.damagedQRButton.Content = qrID;
            Knihotoc_WCFService.Knihotoc_WP7ServiceClient client = new Knihotoc_WCFService.Knihotoc_WP7ServiceClient();
            try
            {
                client.GetBookByIDCompleted += client_GetBookByIDCompleted;
                client.GetBookByIDAsync(Convert.ToInt32(qrID));
            }
            catch
            {
                return;
            }
        }

        private void DamagedQRButton_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Pages/BookFindBookDetailPage.xaml", UriKind.Relative));
        }
    }
}